/**
 * Copyright (C) 2008  Paul Boonyarungsrit
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.tboonyar.maven.plugin.portletcontainer;

import java.io.File;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

/**
 * Abstract goal that provides common configuration for portlet-container's build targets.
 * 
 * @author Paul Boonyarungsrit
 */
public abstract class AbstractPortletContainerMojo
    extends AbstractMojo
{

    /**
     * Portlet Container Home.
     * 
     * @parameter expression = "${portletContainerHome}"
     * @required
     */
    private String portletContainerHome;

    public AbstractPortletContainerMojo()
    {
        super();
    }

    public void execute()
        throws MojoExecutionException
    {
        String buildPath = portletContainerHome + "/bin/build.xml";

        getLog().debug( buildPath );

        Project project = new Project();
        project.setUserProperty( "ant.file", new File( buildPath ).getAbsolutePath() );

        configureProperties( project );

        project.init();
        ProjectHelper helper = ProjectHelper.getProjectHelper();
        project.addReference( "ant.projectHelper", helper );
        helper.parse( project, new File( buildPath ) );

        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream( System.err );
        consoleLogger.setOutputPrintStream( System.out );
        consoleLogger.setMessageOutputLevel( getLog().isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO );
        project.addBuildListener( consoleLogger );

        try
        {
            project.fireBuildStarted();
            project.executeTarget( getTarget() );
            project.fireBuildFinished( null );
        }
        catch ( BuildException e )
        {
            project.fireBuildFinished( e );
        }
    }

    abstract void configureProperties( final Project project );

    abstract String getTarget();

}